#!/bin/sh
# Start/stop/restart webhook.

. /etc/default/webhook

__start() {
	if [ -z "$PIDFILE" ]; then
		echo "WebHook will start but please set PIDFILE in /etc/default/webhook"
	else
		if [ -f "$PIDFILE" ]; then
			echo "WebHook daemon is already running as PID $(< ${PIDFILE}) " >&2
			exit 3
		fi
	fi

	if [ -x /usr/sbin/webhook-wrapper.sh ]; then
		echo "Starting WebHook daemon:  /usr/sbin/webhook-wrapper.sh &"

		if [ -z "$LOG" ]; then
			/usr/sbin/webhook-wrapper.sh > /dev/null 2>&1 &
		else
			/usr/sbin/webhook-wrapper.sh >> "$LOG" 2>&1 &
		fi
	fi
}

__stop() {
	if [ -f "$PIDFILE" ]; then
		kill "$(< ${PIDFILE})"
		rm -f "${PIDFILE}"
	else
		if [ -z "$PIDFILE" ]; then
			killall -9 webhook-wrapper.sh
			killall -9 webhook
		else
			echo "Webhook is not running"
		fi
	fi
}

__restart() {
	__stop
	if [ -z "$PIDFILE" ]; then
		sleep 1
	else
		while [ -f "$PIDFILE" ]; do
			sleep 1
		done
	fi
	__start
}


case "$1" in
	'start')
		__start
		;;
	'stop')
		__stop
		;;
	'restart')
		__restart
		;;
	*)
		echo "usage $0 start|stop|restart"
		exit 2
esac

# vim: ft=sh noet ai ts=4 sw=4 sts=4:
